﻿namespace Cmn.Mis
{
    using Cmn;
    using Cmn.Cls;
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Drawing;
    using System.Runtime.CompilerServices;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    public class DetailControl : UserControl
    {
        private List<string> _DelKeyValueLst;
        private DataTable _DtRecLst;
        private bool _IsModify = false;
        private string _KeyField = "";
        private string _MainKeyField = "";
        private string _TableName = "";
        private ImageButton btnAdd = new ImageButton();
        private ImageButton btnCancel = new ImageButton();
        private ImageButton btnDel = new ImageButton();
        private ImageButton btnModify = new ImageButton();
        private ImageButton btnReturn = new ImageButton();
        private ImageButton btnSave = new ImageButton();
        private GridView gvwRecLst = new GridView();
        private Label lblHeadTitle = new Label();
        private Label lblMainPanelTitle = new Label();
        private Panel pnlButton = new Panel();
        private Panel pnlDisplay = new Panel();
        private Panel pnlEdit = new Panel();
        private Panel pnlHead = new Panel();
        private Panel pnlMain = new Panel();
        private Panel pnlMainBg = new Panel();
        private Panel pnlMainTitle = new Panel();

        public event EventHandler EditComplete;

        public DetailControl()
        {
            this.lblHeadTitle.Text = "明细记录列表";
            this.lblHeadTitle.Font.Size = 12;
            this.pnlHead.Controls.Add(this.lblHeadTitle);
            this.pnlHead.Controls.Add(UI.GetBlank(2));
            ImageButton child = new ImageButton();
            child.Click += new ImageClickEventHandler(this.btnEdit_Click);
            child.ImageUrl = "/CmnRes/images/btnEdit.gif";
            this.pnlHead.Controls.Add(child);
            this.gvwRecLst.EmptyDataText = "记录为空！";
            this.gvwRecLst.AutoGenerateColumns = false;
            this.gvwRecLst.AllowPaging = true;
            this.gvwRecLst.AllowSorting = true;
            this.gvwRecLst.AutoGenerateSelectButton = true;
            this.gvwRecLst.SelectedRowStyle.BackColor = Color.LightBlue;
            this.gvwRecLst.HeaderStyle.BackColor = Color.FromArgb(0x8080c0);
            this.gvwRecLst.HeaderStyle.ForeColor = Color.White;
            this.gvwRecLst.HeaderStyle.BorderColor = Color.Black;
            this.gvwRecLst.HeaderStyle.Font.Bold = false;
            this.gvwRecLst.RowStyle.BackColor = Color.White;
            this.gvwRecLst.AlternatingRowStyle.BackColor = Color.FromArgb(0xeff1f7);
            this.gvwRecLst.PageIndexChanging += new GridViewPageEventHandler(this.gvwRecLst_PageIndexChanging);
            this.gvwRecLst.SelectedIndexChanging += new GridViewSelectEventHandler(this.gvwRecLst_SelectedIndexChanging);
            this.pnlDisplay.Controls.Add(this.gvwRecLst);
            this.pnlDisplay.Controls.Add(UI.GetBR(2));
            this.btnAdd.Click += new ImageClickEventHandler(this.btnAdd_Click);
            this.btnAdd.ImageUrl = "/CmnRes/images/btnAdd.gif";
            this.pnlButton.Controls.Add(this.btnAdd);
            this.pnlButton.Controls.Add(UI.GetBlank(1));
            this.btnDel.Click += new ImageClickEventHandler(this.btnDel_Click);
            this.btnDel.ImageUrl = "/CmnRes/images/btnDel.gif";
            this.pnlButton.Controls.Add(this.btnDel);
            this.pnlButton.Controls.Add(UI.GetBlank(1));
            this.btnModify.Click += new ImageClickEventHandler(this.btnModify_Click);
            this.btnModify.ImageUrl = "/CmnRes/images/btnModify.gif";
            this.pnlButton.Controls.Add(this.btnModify);
            this.pnlButton.Controls.Add(UI.GetBlank(1));
            this.btnReturn.Click += new ImageClickEventHandler(this.btnReturn_Click);
            this.btnReturn.ImageUrl = "/CmnRes/images/btnReturn.gif";
            this.pnlButton.Controls.Add(this.btnReturn);
            this.pnlDisplay.Controls.Add(this.pnlButton);
            this.pnlDisplay.Style.Add("margin", "1px");
            this.pnlMain.Controls.Add(this.pnlDisplay);
            this.pnlMain.Controls.Add(this.pnlEdit);
            this.pnlEdit.Visible = false;
            this.pnlButton.Visible = false;
            this.pnlMainTitle.Visible = false;
            this.pnlMainBg.Attributes.Add("id", "bgDiv");
            this.pnlMainBg.Style.Add("position", "absolute");
            this.pnlMainBg.Style.Add("top", "0");
            this.pnlMainBg.Style.Add("background", "#777");
            this.pnlMainBg.Style.Add("filter", "progid:DXImageTransform.Microsoft.Alpha(style=3,opacity=25,finishOpacity=75)");
            this.pnlMainBg.Style.Add("opacity", "0.6");
            this.pnlMainBg.Style.Add("left", "0");
            this.pnlMainBg.Style.Add("zIndex", "10000");
            this.pnlMain.Attributes.Add("id", "msgDiv");
            this.pnlMainTitle.Attributes.Add("id", "msgTitle");
            this.pnlMainTitle.Attributes.Add("align", "left");
            this.pnlMainTitle.Style.Add("margin", "10");
            this.pnlMainTitle.Style.Add("padding", "3px");
            this.pnlMainTitle.Style.Add("background", "#336699");
            this.pnlMainTitle.Style.Add("filter", "progid:DXImageTransform.Microsoft.Alpha(startX=20, startY=20, finishX=100, finishY=100,style=1,opacity=75,finishOpacity=100);");
            this.pnlMainTitle.Style.Add("opacity", "0.75");
            this.pnlMainTitle.Style.Add("border", "1px solid #336699");
            this.pnlMainTitle.Style.Add("height", "18px");
            this.pnlMainTitle.Style.Add("font", "12px Verdana, Geneva, Arial, Helvetica, sans-serif");
            this.pnlMainTitle.Style.Add("color", "white");
            this.pnlMainTitle.Style.Add("cursor", "pointer");
            this.lblMainPanelTitle.Text = "明细记录管理";
            this.pnlMainTitle.Controls.Add(this.lblMainPanelTitle);
            this.pnlMain.Controls.AddAt(0, this.pnlMainTitle);
            base.Init += new EventHandler(this.DetailControl_Init);
            base.Load += new EventHandler(this.DetailControl_Load);
            base.PreRender += new EventHandler(this.DetailControl_PreRender);
        }

        public void AddCol(string colName, string colTitle)
        {
            this._DtRecLst.Columns.Add(colName);
            this._DtRecLst.Columns[colName].Caption = colTitle;
            BoundField field = new BoundField {
                HeaderText = colTitle,
                DataField = colName,
                SortExpression = colName
            };
            this.gvwRecLst.Columns.Add(field);
            this.ViewState.Add("RecLst", this._DtRecLst);
        }

        public void AddCol(string colName, string colTitle, int colWidth)
        {
            this._DtRecLst.Columns.Add(colName);
            this._DtRecLst.Columns[colName].Caption = colTitle;
            BoundField field = new BoundField {
                HeaderText = colTitle,
                DataField = colName,
                SortExpression = colName,
                HeaderStyle = { Width = colWidth }
            };
            this.gvwRecLst.Columns.Add(field);
            this.ViewState.Add("RecLst", this._DtRecLst);
        }

        private void btnAdd_Click(object sender, ImageClickEventArgs e)
        {
            this._IsModify = false;
            this.ViewState.Add("IsModify", "0");
            UI.InitControls(this.pnlEdit);
            this.ShowMainPanel(TViewState.Add);
        }

        private void btnCancel_Click(object sender, ImageClickEventArgs e)
        {
            this.ShowMainPanel(TViewState.RecList);
        }

        private void btnDel_Click(object sender, ImageClickEventArgs e)
        {
            if ((this.gvwRecLst.SelectedIndex < 0) || (this.gvwRecLst.SelectedIndex > (this.gvwRecLst.Rows.Count - 1)))
            {
                Js.Alert(this.Page, "没有选中记录！请选择记录。");
                this.ShowMainPanel(TViewState.RecList);
            }
            else
            {
                if (this._DtRecLst.Rows[this.gvwRecLst.SelectedIndex][this._KeyField].ToString().Trim() != "")
                {
                    this._DelKeyValueLst.Add(this._DtRecLst.Rows[this.gvwRecLst.SelectedIndex][this._KeyField].ToString().Trim());
                }
                this._DtRecLst.Rows.RemoveAt(this.gvwRecLst.SelectedIndex);
                this.gvwRecLst.DataBind();
                this.ShowMainPanel(TViewState.RecList);
            }
        }

        private void btnEdit_Click(object sender, ImageClickEventArgs e)
        {
            this.pnlButton.Visible = true;
            this.ShowMainPanel(TViewState.RecList);
        }

        private void btnModify_Click(object sender, ImageClickEventArgs e)
        {
            if ((this.gvwRecLst.SelectedIndex < 0) || (this.gvwRecLst.SelectedIndex > (this.gvwRecLst.Rows.Count - 1)))
            {
                Js.Alert(this.Page, "没有选中记录！请选择记录。");
                this.ShowMainPanel(TViewState.RecList);
            }
            else
            {
                this._IsModify = true;
                this.ViewState.Add("IsModify", "1");
                TableInfo tableInfo = new TableInfo();
                TableOpt.GetTableInfo(tableInfo, this.gvwRecLst);
                TableOpt.SetControlValue(this.pnlEdit, tableInfo);
                this.ShowMainPanel(TViewState.Modify);
            }
        }

        private void btnReturn_Click(object sender, ImageClickEventArgs e)
        {
            this.pnlMainBg.Visible = false;
            this.pnlButton.Visible = false;
            this.pnlMainTitle.Visible = false;
            this.pnlMain.Style.Clear();
            if (this.EditComplete != null)
            {
                this.EditComplete(sender, e);
            }
        }

        private void btnSave_Click(object sender, ImageClickEventArgs e)
        {
            TableInfo tableInfo = new TableInfo {
                TableName = this._TableName
            };
            TableOpt.GetTableInfo(this.pnlEdit, tableInfo);
            string errorMsg = "";
            //if (!FieldCheck.CheckTableInfo(tableInfo, ref errorMsg))
            //{
            //    Js.Alert(this.Page, errorMsg);
            //    if (this._IsModify)
            //    {
            //        this.ShowMainPanel(TViewState.Modify);
            //    }
            //    else
            //    {
            //        this.ShowMainPanel(TViewState.Add);
            //    }
            //}
            //else
            //{
                string str;
                int num;
                UI.GetDescList(tableInfo.FieldValueList, this.pnlEdit);
                if (this._IsModify)
                {
                    for (num = 0; num < this._DtRecLst.Columns.Count; num++)
                    {
                        if (tableInfo.FieldValueList.TryGetValue(this._DtRecLst.Columns[num].ColumnName.ToLower(), out str))
                        {
                            this._DtRecLst.Rows[(this.gvwRecLst.PageIndex * this.gvwRecLst.PageSize) + this.gvwRecLst.SelectedIndex][num] = str;
                        }
                    }
                }
                else
                {
                    DataRow row = this._DtRecLst.NewRow();
                    for (num = 0; num < this._DtRecLst.Columns.Count; num++)
                    {
                        if (tableInfo.FieldValueList.TryGetValue(this._DtRecLst.Columns[num].ColumnName.ToLower(), out str))
                        {
                            row[this._DtRecLst.Columns[num].ColumnName] = str;
                        }
                    }
                    this._DtRecLst.Rows.Add(row);
                }
                this.gvwRecLst.DataBind();
                this.ShowMainPanel(TViewState.RecList);
            //}
        }

        public int DelData(string mainKeyValue)
        {
            if (DB.execSql("delete from " + this._TableName + " where " + this._MainKeyField + "='" + mainKeyValue + "'"))
            {
                return 0;
            }
            return -1;
        }

        private void DetailControl_Init(object sender, EventArgs e)
        {
            while (this.Controls.Count > 0)
            {
                this.pnlEdit.Controls.Add(this.Controls[0]);
            }
            this.pnlEdit.Controls.Add(UI.GetBR(2));
            this.btnSave.Click += new ImageClickEventHandler(this.btnSave_Click);
            this.btnSave.ImageUrl = "/CmnRes/images/btnSave.gif";
            this.pnlEdit.Controls.Add(this.btnSave);
            this.pnlEdit.Controls.Add(UI.GetBlank(1));
            this.btnCancel.Click += new ImageClickEventHandler(this.btnCancel_Click);
            this.btnCancel.ImageUrl = "/CmnRes/images/btnCancel.gif";
            this.pnlEdit.Controls.Add(this.btnCancel);
            this.pnlEdit.Style.Add("margin", "1px");
            this.Controls.Add(this.pnlHead);
            this.Controls.Add(UI.GetBR(1));
            this.Controls.Add(this.pnlMain);
            this.Controls.AddAt(0, this.pnlMainBg);
        }

        private void DetailControl_Load(object sender, EventArgs e)
        {
            if (this.ViewState["RecLst"] == null)
            {
                this._DtRecLst = new DataTable();
            }
            else
            {
                this._DtRecLst = (DataTable) this.ViewState["RecLst"];
            }
            this.gvwRecLst.DataSource = this._DtRecLst;
            if (this.ViewState["DelKeyValueLst"] == null)
            {
                this._DelKeyValueLst = new List<string>();
            }
            else
            {
                this._DelKeyValueLst = (List<string>) this.ViewState["DelKeyValueLst"];
            }
            this.gvwRecLst.DataBind();
            if (this.ViewState["SelectedIndex"] != null)
            {
                this.gvwRecLst.SelectedIndex = Convert.ToInt32(this.ViewState["SelectedIndex"].ToString());
            }
            if (this.ViewState["PageIndex"] != null)
            {
                this.gvwRecLst.PageIndex = Convert.ToInt32(this.ViewState["PageIndex"].ToString());
                this.gvwRecLst.DataBind();
            }
            if (this.ViewState["SelectSql"] != null)
            {
                this._TableName = SqlAnalyse.GetMainTableName(this.ViewState["SelectSql"].ToString());
                this._KeyField = SqlAnalyse.GetKeyField(this.ViewState["SelectSql"].ToString());
            }
            if (this.ViewState["MainKeyField"] != null)
            {
                this._MainKeyField = this.ViewState["MainKeyField"].ToString();
            }
            if (this.ViewState["IsModify"] != null)
            {
                if (this.ViewState["IsModify"].ToString() == "1")
                {
                    this._IsModify = true;
                }
                else
                {
                    this._IsModify = false;
                }
            }
            if ((this._TableName != null) && (UI.SetControlJs(this._TableName, this.pnlEdit) > 0))
            {
                Js.Import(this.Page, "/CmnRes/fieldcheck.js", true);
            }
        }

        private void DetailControl_PreRender(object sender, EventArgs e)
        {
            this.ViewState.Add("RecLst", this._DtRecLst);
            this.ViewState.Add("DelKeyValueLst", this._DelKeyValueLst);
        }

        public void Display(string strSql, string mainKeyField)
        {
            this._MainKeyField = mainKeyField;
            this._TableName = SqlAnalyse.GetMainTableName(strSql);
            this._KeyField = SqlAnalyse.GetKeyField(strSql);
            this.ViewState.Add("SelectSql", strSql);
            this.ViewState.Add("MainKeyField", this._MainKeyField);
        }

        public string GetField(int rowNo, int fieldNo)
        {
            return this._DtRecLst.Rows[rowNo][fieldNo].ToString();
        }

        public int GetRowCount()
        {
            return this._DtRecLst.Rows.Count;
        }

        private void gvwRecLst_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.gvwRecLst.PageIndex = e.NewPageIndex;
            this.gvwRecLst.DataBind();
            this.ViewState["PageIndex"] = e.NewPageIndex;
            this.ShowMainPanel(TViewState.RecList);
        }

        private void gvwRecLst_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
        {
            this.gvwRecLst.SelectedIndex = e.NewSelectedIndex;
            this.ViewState["SelectedIndex"] = e.NewSelectedIndex;
            this.ShowMainPanel(TViewState.RecList);
        }

        public void InitControl()
        {
            this._DtRecLst.Clear();
            this.gvwRecLst.DataBind();
        }

        public int LoadData(string mainKeyValue)
        {
            DataTable table = DB.getDataTable(SqlAnalyse.AddWhere(this.ViewState["SelectSql"].ToString(), this._MainKeyField + "='" + mainKeyValue + "'"));
            this._DtRecLst.Clear();
            for (int i = 0; i < table.Rows.Count; i++)
            {
                DataRow row = this._DtRecLst.NewRow();
                for (int j = 0; j < this._DtRecLst.Columns.Count; j++)
                {
                    string columnName = this._DtRecLst.Columns[j].ColumnName;
                    row[columnName] = table.Rows[i][columnName];
                }
                this._DtRecLst.Rows.Add(row);
            }
            this.gvwRecLst.DataBind();
            return 0;
        }

        public int SaveData(string mainKeyValue)
        {
            int num;
            for (num = 0; num < this._DelKeyValueLst.Count; num++)
            {
                if (!DB.execSql("delete from " + this._TableName + " where " + this._KeyField + "='" + this._DelKeyValueLst[num] + "'"))
                {
                    return -1;
                }
            }
            this._DelKeyValueLst.Clear();
            TableInfo tableInfo = new TableInfo {
                TableName = this._TableName,
                KeyField = this._KeyField
            };
            for (num = 0; num < this._DtRecLst.Rows.Count; num++)
            {
                tableInfo.FieldValueList.Clear();
                TableOpt.GetTableInfo(tableInfo, this._DtRecLst, num);
                tableInfo.FieldValueList.Remove(this._KeyField.ToLower());
                tableInfo.FieldValueList.Add(this._MainKeyField.ToLower(), mainKeyValue);
                if (this._DtRecLst.Rows[num][this._KeyField].ToString().Trim() != "")
                {
                    if (TableOpt.Update(tableInfo, this._DtRecLst.Rows[num][this._KeyField].ToString().Trim()) != 0)
                    {
                        return -1;
                    }
                }
                else if (TableOpt.Insert(tableInfo) != 0)
                {
                    return -1;
                }
            }
            return 0;
        }

        private void ShowMainPanel(TViewState viewState)
        {
            this.pnlMainBg.Visible = true;
            this.pnlMainTitle.Visible = true;
            this.pnlButton.Visible = true;
            int num = 600;
            int num2 = 400;
            this.pnlMain.Style.Add("background", "white");
            this.pnlMain.Style.Add("border", "1px solid #336699");
            this.pnlMain.Style.Add("position", "absolute");
            this.pnlMain.Style.Add("left", "50px");
            this.pnlMain.Style.Add("top", "50px");
            this.pnlMain.Style.Add("font", "12px/1.6em Verdana, Geneva, Arial, Helvetica, sans-serif");
            this.pnlMain.Style.Add("width", num + "px");
            this.pnlMain.Style.Add("height", num2 + "px");
            this.pnlMain.Style.Add("margin", "100");
            this.pnlMain.Style.Add("marginTop", "-100");
            this.pnlMain.Style.Add("lineHeight", "25px");
            this.pnlMain.Style.Add("zIndex", "10001");
            Js.Run(this.Page, "var sWidth,sHeight;\r\n                sWidth=document.body.offsetWidth;\r\n                sHeight=screen.height;\r\n                document.getElementById('bgDiv').style.width=sWidth + 'px';\r\n                document.getElementById('bgDiv').style.height=sHeight + 'px';", false);
            switch (viewState)
            {
                case TViewState.RecList:
                    this.lblMainPanelTitle.Text = "明细记录管理（记录列表）";
                    this.pnlDisplay.Visible = true;
                    this.pnlEdit.Visible = false;
                    break;

                case TViewState.Delete:
                    this.lblMainPanelTitle.Text = "明细记录管理（删除记录）";
                    break;

                case TViewState.Add:
                    this.lblMainPanelTitle.Text = "明细记录管理（增加记录）";
                    this.pnlDisplay.Visible = false;
                    this.pnlEdit.Visible = true;
                    break;

                case TViewState.Modify:
                    this.lblMainPanelTitle.Text = "明细记录管理（修改记录）";
                    this.pnlDisplay.Visible = false;
                    this.pnlEdit.Visible = true;
                    break;
            }
        }

        public string Title
        {
            get
            {
                return this.lblHeadTitle.Text;
            }
            set
            {
                this.lblHeadTitle.Text = value;
            }
        }

        private enum TViewState
        {
            RecList,
            Delete,
            Add,
            Modify
        }
    }
}

